package com.bear.fastrepair.mvvm.ui.employee.adapter

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bear.fastrepair.base.BaseViewHolder
import com.bear.fastrepair.databinding.ItemOrderEmployeeBinding
import com.bear.fastrepair.databinding.ItemOrderEmployeeFooterBinding
import com.bear.fastrepair.entity.FooterItem
import com.bear.fastrepair.entity.ItemTypeOrder
import com.bear.fastrepair.entity.Record
import com.bear.fastrepair.entity.RecordItem
import com.bear.fastrepair.mvvm.ui.employee.EmployeeViewModel
import com.bear.fastrepair.utils.CLOCK_IN
import com.bear.fastrepair.utils.LocationHelper
import com.bear.fastrepair.utils.OpenLocalMapUtil
import com.bear.fastrepair.utils.launch
import com.blankj.utilcode.util.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class OrderAdapter(
    val data: ArrayList<ItemTypeOrder>,
    private val viewModel: EmployeeViewModel,
    private val context: Context
) :
    RecyclerView.Adapter<BaseViewHolder<*>>() {

    var itemClick: ((Record, Int) -> Unit)? = null

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): BaseViewHolder<*> {
        return when (viewType) {
            0 -> RecordViewHolder(
                ItemOrderEmployeeBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
            1 -> FooterViewHolder(
                ItemOrderEmployeeFooterBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
            else -> throw RuntimeException("no such view type")
        }
    }

    override fun onBindViewHolder(holder: BaseViewHolder<*>, position: Int) {
        if (data.isEmpty()) return
        if (holder is RecordViewHolder) {
            holder.bind(data[position] as RecordItem, position)
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun getItemViewType(position: Int): Int {
        return data[position].itemType
    }

    inner class RecordViewHolder(private val binding: ItemOrderEmployeeBinding) :
        BaseViewHolder<RecordItem>(binding.root) {
        @SuppressLint("SetTextI18n")
        override fun bind(item: RecordItem, index: Int) {
            binding.address.text = "${item.record.locationAddress}${item.record.addressDetail}"
            binding.orderStatus.text = item.record.serviceOrderStatusText
            binding.clientName.text = item.record.clientName
            binding.clientTel.text = item.record.clientTel
            binding.orderNumber.text = item.record.orderNo
            binding.orderTitle.text = item.record.description
            if (item.record.serviceOrderStatus >= CLOCK_IN) {
                binding.clockIn.isEnabled = false
            }
            binding.clockIn.setOnClickListener {
                viewModel.launch {
                    withContext(Dispatchers.IO) {
                        LocationHelper.getLocationInfo(context) {
                            it ?: run {
                                ToastUtils.showLong("定位信息获取失败，请检查定位权限并重试")
                                return@getLocationInfo
                            }
                            viewModel.employeeClockIn(
                                it.address,
                                locationLatitude = "${it.latitude}",
                                locationLongitude = "${it.longitude}",
                                item.record.id,
                                index
                            )
                        }
                    }
                }
            }
            binding.callLl.setOnClickListener {
                val intent = Intent().apply {
                    action = Intent.ACTION_DIAL
                    data = Uri.parse("tel:${item.record.clientTel}")
                }
                ActivityUtils.startActivity(intent)
            }
            binding.mapLl.setOnClickListener {
                try {
                    val latitude = viewModel.personalInfo.value?.data?.locationLatitude
                    val longitude = viewModel.personalInfo.value?.data?.locationLongitude
                    val address = viewModel.personalInfo.value?.data?.locationAddress
                    val destination = item.record.locationAddress
                    val destinationLatitude = item.record.locationLatitude
                    val destinationLongitude = item.record.locationLongitude
                    val uri = OpenLocalMapUtil.getGdMapUri("小熊快修", latitude, longitude, address, destinationLatitude.toString(),
                        destinationLongitude.toString(), destination)
                    val intent = Intent(Intent.ACTION_VIEW).apply {
                        val uriString = "androidamap://navi?sourceApplication=${"小熊快修"}&lat=$destinationLatitude&lon=$destinationLongitude&dev=1&style=2"
                        addCategory(Intent.CATEGORY_DEFAULT)
                        setPackage("com.autonavi.minimap")
                        data = Uri.parse(uri)
                    }
                    context.startActivity(intent)
                } catch (e: ActivityNotFoundException) {
                    ToastUtils.showLong("请下载高德地图以使用导航")
                }
            }
            if (item.record.newOrNot) binding.ivNew.visibility = View.VISIBLE
            binding.detail.setOnClickListener {
                itemClick?.invoke(item.record, index)
            }
        }
    }

    inner class FooterViewHolder(private val binding: ItemOrderEmployeeFooterBinding) :
        BaseViewHolder<FooterItem>(binding.root) {
        override fun bind(item: FooterItem, index: Int) = Unit
    }
}